<?php
namespace Common\Model;
use Think\Model;

class OrderModel extends Model{
	public $count    = 0;
	public $pagesize = 10;
	public $is_saas_order = false;

	/**
	 * 提交订单
	 * @param  integer $user_id      用户ID
	 * @param  string  $agreement_id 合同ID
	 * @param  string  $demand       需求说明
	 */
	public function submit($user_id = 0, $agreement_id = '', $demand = '', $is_package = 0){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		$user_info = D('User')->user_info($user_id);
		if(!$user_info['status']){
			$this->tips_info = '您的账号被禁用，请联系相关人员！';
			return false;
		}
		$agreement_info = D('CustomAgreement')->info($agreement_id);
		if(!$agreement_info){
			$this->tips_info = '合同不存在！';
			return false;
		}
		// 合同价格
		$service_price = $agreement_info['service_price'];
		// 套餐价格
		$package_price = $agreement_info['package_price'];
		// 套餐合同ID
		$package_agreement_ids = $agreement_info['package_agreement_ids'];
		if($is_package && (!$package_agreement_ids || !$package_price)){
			$this->tips_info = '对不起，此合同未配置套餐！';
			return false;
		}
		// 订单金额
		$order_amount = $is_package ? $package_price : $service_price;
		// 生成订单号
		$order_sn = generate_order_sn();
		// 创建订单信息
		$data['order_sn']              = $order_sn;
		$data['user_id']               = $user_id;
		$data['saas_enterprise_id']    = $user_info['saas_enterprise_id'];
		$data['saas_user_id']          = $user_info['saas_user_id'];
		$data['province_id']           = $user_info['province_id'];
		$data['city_id']               = $user_info['city_id'];
		$data['agreement_id']          = $agreement_id;
		$data['title']                 = $agreement_info['title'];
		$data['category_id']           = $agreement_info['category_id'];
		$data['service_user_id']       = $agreement_info['service_user_id'] ? $agreement_info['service_user_id'] : 0;
		$data['audit_user_id']         = $agreement_info['audit_user_id'] ? $agreement_info['audit_user_id'] : 0;
		$data['order_amount']          = $order_amount ? $order_amount : 0;
		$data['demand']                = $demand ? $demand : '';
		$data['is_package']            = $is_package ? $is_package : 0;
		$data['package_agreement_ids'] = $package_agreement_ids ? $package_agreement_ids : '';
		$data['create_time']           = time();
		$data['edit_time']             = time();
		$data['status']                = 'doing-service';//下单，等待客服处理
		$this->add($data);
		// 记录订单操作记录
		$this->opt_logs($order_sn, '用户下单', $user_id);
		// 更新制定合同下单数量
		D('CustomAgreement')->update_order_num($agreement_id);
		$order_notice_mobile = Conf('order_notice_mobile');
		$order_notice_mobile_arr = explode(PHP_EOL, $order_notice_mobile);
		$order_notice_mobile_str = str_replace(array("\n", "\r"), '', implode(',', $order_notice_mobile_arr));
		if($order_notice_mobile_str){
			$sms_content = '新订单：[' . $order_sn . ']' . $data['title'] . '，金额：' . $data['order_amount'] . '联系人：' . $user_info['realname'] . '(' . $user_info['mobile'] . ')' . '，请处理';
			D('Sms')->send($order_notice_mobile_str, $sms_content);
		}
		// 消息提醒
		D('Message')->order_msg_push($order_sn, 'submit_doing_service');

		return $order_sn;
	}
	/**
	 * 提交免费订单
	 * @param  [type] $user_id      用户ID
	 * @param  [type] $agreement_id 合同ID
	 */
	public function submit_free_order($user_id, $agreement_id){
		if(!$user_id || !$agreement_id){
			$this->tips_info = '用户ID或合同ID不能为空！';
			return false;
		}
		$ask_answer = D('FreeAgreement')->get_ask_answer($user_id, $agreement_id);
		if(!$ask_answer){
			$this->tips_info = '您尚未填写相关问答！';
			return false;
		}
		$user_info = D('User')->user_info($user_id);
		if(!$user_info['status']){
			$this->tips_info = '您的账号被禁用，请联系相关人员！';
			return false;
		}

		$ask_answer_serialize = serialize($ask_answer);
		$order_md5 = md5($user_id . '-' . $agreement_id . '-' . $ask_answer_serialize);
		$order_sn  = generate_order_sn();
		$info      = D('FreeAgreement')->where(array('id' => $agreement_id))->find();
		if(!$info || $info['status'] == 0 || $info['is_delete'] == 1){
			$this->tips_info = '合同不存在！';
			return false;
		}

		$data['order_sn']     = $order_sn;
		$data['title']        = $info['title'];
		$data['user_id']      = $user_id;
		$data['province_id']  = $user_info['province_id'];
		$data['city_id']      = $user_info['city_id'];
		$data['agreement_id'] = $agreement_id;
		$data['type']         = $info['type'];
		$data['category_id']  = $info['category_id'];
		$data['ask_answer']   = $ask_answer_serialize;
		$data['md5']          = $order_md5;
		$data['create_time']  = time();

		if(!D('FreeOrder')->where(array('md5' => $order_md5))->count()){
			// 生成订单限制
			if($this->get_user_today_free_num($user_id) > 5){
				$this->tips_info = '对不起，一天只能生成5个不同的合同！';
				return false;
			}
			D('FreeOrder')->add($data);
			D('FreeAgreement')->where(array('id' => $agreement_id))->setInc('save_num');
		}
		return true;
	}
	public function get_user_today_free_num($user_id){
		$where['create_time'][] = array('egt', strtotime(date('Y-m-d 00:00:00')));
		$where['create_time'][] = array('elt', strtotime(date('Y-m-d 24:00:00')));
		$where['user_id']       = $user_id;
		$data  = D('FreeOrder')->field('count(DISTINCT(agreement_id)) num')->where($where)->find();
		$count = $data['num'];

		return $count;
	}
	/**
	 * 获取订单问答数据
	 * @param  string $order_sn 订单号
	 */
	public function get_ask_answer($order_sn = ''){
		if(!$order_sn){
			return false;
		}
		$where['order_sn'] = $order_sn;
		$ask_answer = D('FreeOrder')->where($where)->getField('ask_answer');
		$ask_answer = unserialize($ask_answer);

		return $ask_answer ? $ask_answer : array();
	}
	/**
	 * 获取免费订单数量
	 */
	public function get_free_order_num(){
		$count = D('FreeOrder')->count();

		return $count ? $count + 6231 : 6231;
	}
	/**
	 * 订单详情
	 * @param  string $order_sn 订单号
	 */
	public function info($order_sn = ''){
		if(!$order_sn){
			return false;
		}
		$where['order_sn'] = $order_sn;
		$info = $this->where($where)->find();
		$info = $this->filter_field($info);
		$info['audit_comment_info']  = D('Comment')->get_order_comment_info($order_sn, 'audit_comment');
		$info['user_comment_info']   = D('Comment')->get_order_comment_info($order_sn, 'user_comment');
		$info['opt_logs_list']       = $this->get_opt_logs_list($order_sn);
		// 合同文件，律师可看
		$info['agreement_file_list'] = D('File')->get_file_list($info['agreement_file_ids']);
		$info['finish_file_list']    = D('File')->get_file_list($info['finish_file_ids']);

		return $info;
	}
	/**
	 * 获取订单列表
	 * @param  array   $where    where条件
	 * @param  string  $order    排序
	 * @param  integer $page     第几页
	 * @param  integer $pagesize 分页数量
	 */
	public function get_list($where, $order = '', $page = 1, $pagesize = 0){
		$pagesize  = $pagesize ? $pagesize : $this->pagesize;
		$first_row = $pagesize * ($page - 1);

		//默认排序
		if(!$order){
			$order['create_time'] = 'desc';
		}

		$count = $this->where($where)->count();
		$list  = $this->where($where)->limit($first_row . ',' . $pagesize)->order($order)->select();
		foreach ($list as $rs) {
			$new_list[] = $this->filter_field($rs);
		}
		$this->count = $count;
		return $new_list ? $new_list : array();
	}
	public function filter_field($info = ''){
		
		$info['province_name']  = D('Area')->id2names($info['province_id']);
		$info['city_name']      = D('Area')->id2names($info['city_id']);
		$info['category_name']  = D('Category')->get_name($info['category_id']);
		$info['agreement_info'] = D('CustomAgreement')->info($info['agreement_id']);

		// 套餐合同名称
		$info['package_agreement_name'] = D('CustomAgreement')->get_name($info['package_agreement_ids'], '+');
		// 用户信息
		$user_info = D('User')->user_info($info['user_id']);
		$info['user_info']     = $user_info;
		$info['user_name']     = $user_info['realname'];
		$info['user_head_url'] = $user_info['head_url'];
		$info['user_mobile']   = $user_info['mobile'];
		$info['user_email']    = $user_info['email'];

		// 律师信息
		$lawyer_info = $info['lawyer_user_id'] ? D('User')->user_info($info['lawyer_user_id']) : '';
		$info['lawyer_info']   = $lawyer_info;
		$info['lawyer_name']   = $lawyer_info ? $lawyer_info['realname'] : '';
		$info['lawyer_mobile'] = $lawyer_info ? $lawyer_info['mobile'] : '';

		// 用户人员状态说明
		$info['user_status_desc']        = get_type_desc($info['status'], 'user_order_status_desc');
		// 客服人员状态说明
		$info['service_status_desc']     = get_type_desc($info['status'], 'service_order_status_desc');
		// 律师人员状态说明
		$info['lawyer_status_desc']      = get_type_desc($info['status'], 'lawyer_order_status_desc');
		// 审核人员状态说明
		$info['audit_status_desc']       = get_type_desc($info['status'], 'audit_order_status_desc');
		// 订单状态颜色
		$info['status_color']            = get_type_desc($info['status'], 'order_status_color');
		// 订单审核状态
		$info['order_audit_status_desc'] = get_type_desc($info['audit_status'], 'audit_status_desc');
		// 订单审核状态颜色
		$info['audit_status_color']      = get_type_desc($info['audit_status'], 'audit_status_color');

		// 订单时间
		$info['datetime']        = date('Y-m-d H:i:s', $info['create_time']);
		// 支付类型
		$info['pay_type_desc']   = get_pay_type_desc($info['pay_type']);
		// 订单TODO
		$info['todo_list']       = D('Order')->get_todo_list($info['order_sn']);
		// 是否可以取消
		$info['is_cancel']       = in_array($info['status'], C('order_cancel_status'));
		// 是否查看评价
		$info['is_view_comment'] = $info['is_commented'] > 0;
		// 是否可以评价
		$info['is_comment']      = (!$info['is_view_comment'] && $info['status'] == 'finish');
		// 是否可以支付
		$info['is_pay']          = $info['status'] == 'wait_pay';

		// 下载URL
		$finish_file_ids = explode(',', $info['finish_file_ids']);
		if($finish_file_ids[0]){
			$info['download_url'] = D('File')->get_path($finish_file_ids[0]);
			$info['download_id']  = $finish_file_ids[0];
		}

		return $info;
	}
	/**
	 * 律师是否在处理订单
	 * @param  string $user_id 用户ID
	 */
	public function lawyer_is_doing($user_id = ''){
		$where['lawyer_user_id'] = $user_id;
		$where['status']         = array('in', 'doing-lawyer,doing-audit');
		$count = $this->where($where)->count();

		return $count > 0;
	}
	/**
	 * 订单TODO清单
	 * @param  [type] $order_sn 订单号
	 * @param  string $type     类型
	 */
	public function get_todo_list($order_sn, $type = 'lawyer_order_record'){
		$where['order_sn'] = $order_sn;
		$where['type']     = $type;
		$list = D('OrderTodo')->where($where)->order('create_time,id desc')->select();
		foreach ($list as $rs) {
			$rs['datetime'] = date('Y-m-d H:i:s', $rs['create_time']);
			$new_list[] = $rs;
		}

		return $new_list ? $new_list : array();
	}

	/**
	 * 充值订单支付
	 * @param  [type] $pay_type 	支付类型
	 * @param  [type] $order_sn 	订单号
	 * @param  [type] $trade_no     交易号
	 * @param  [type] $total_fee    支付金额
	 * @param  [type] $buyer_email  买方支付账号
	 * @param  [type] $buyer_id     买方ID
	 * @param  [type] $seller_email 卖方账号
	 */
	public function order_pay($pay_type = 'alipay', $order_sn, $trade_no, $total_fee, $buyer_email, $buyer_id, $seller_email){
		//获取充值订单信息
		$where['order_sn'] = $order_sn;
		$order = D('Order')->where($where)->find();
		$user_id      = $order['user_id'] ? $order['user_id'] : 0;
		$province_id  = $order['province_id'] ? $order['province_id'] : 0;
		$city_id      = $order['city_id'] ? $order['city_id'] : 0;
		$app_type     = $order['app_type'] ? $order['app_type'] : '';
		$agreement_id = $order['agreement_id'];

		$data['province_id']  = $province_id;
		$data['city_id']      = $city_id;
		$data['user_id']      = $user_id;
		$data['order_type']   = 'agreement_order';//合同订单
		$data['pay_type']     = $pay_type;
		$data['order_sn']     = $order_sn;
		$data['trade_no']     = $trade_no;
		$data['total_fee']    = $total_fee;
		$data['buyer_email']  = $buyer_email ? $buyer_email : '';
		$data['buyer_id']     = $buyer_id ? $buyer_id : '';
		$data['seller_email'] = $seller_email ? $seller_email : '';
		$data['create_time']  = time();

		unset($where);
		$where['order_sn'] = $order_sn;
		$where['trade_no'] = $trade_no;
		if(!D('OrderPay')->where($where)->count()){
			D('OrderPay')->add($data);
			//更新充值订单信息
			$order_data['pay_time']     = time();
			$order_data['edit_time']    = time();
			$order_data['status']       = 'doing-lawyer';//支付成功，到律师处理
			$order_data['payed_amount'] = $total_fee;
			D('Order')->where($where)->save($order_data);
			// 打款给用户冻结账户上
			D('Account')->pay_order($pay_type, $user_id, $order_sn, $agreement_id, $total_fee, $order['title']);
			// 记录订单操作记录
			$this->opt_logs($order_sn, '用户支付', $user_id);

			// 消息提醒
			D('Message')->order_msg_push($order_sn, 'payed');
			return true;
		}
		return false;
	}
	public function cancel($order_sn){
		$info = D('Order')->info($order_sn);
		if(!$info['is_cancel']){
			$this->tips_info = '对不起，此订单状态不能取消！';
			return false;
		}
		$user_id = $info['user_id'];
		// 已支付订单处理
		if($info['payed_amount'] > 0){
			D('Account')->cancel_order($user_id, $order_sn, $info['agreement_id'], $info['payed_amount'], $info['title']);
		}
		// 更新订单状态
		$data['cancel_time'] = time();
		$data['edit_time']   = time();
		$data['status']      = 'cancel';
		D('Order')->where(array('order_sn' => $order_sn))->save($data);
		// 记录订单操作记录
		$this->opt_logs($order_sn, '取消订单', $user_id);

		// 消息提醒
		D('Message')->order_msg_push($order_sn, 'cancel');
		return true;
	}
	/**
	 * 订单操作日志
	 * @param  [type] $user_name 用户名
	 * @param  string $info      操作信息
	 */
	public function opt_logs($order_sn, $info = '', $user_id, $user_name){
		$data['order_sn']    = $order_sn;
		$data['user_id']     = $user_id ? $user_id : 0;
		$data['user_name']   = $user_name ? $user_name : D('User')->where(array('user_id' => $user_id))->getField('realname');
		$data['info']        = $info ? $info : '';
		$data['create_time'] = time();
		D('OrderOptLogs')->add($data);
	}
	/**
	 * 获取订单操作记录
	 * @param  [type] $order_sn 订单号
	 */
	public function get_opt_logs_list($order_sn){
		$where['order_sn'] = $order_sn;
		$list = D('OrderOptLogs')->where($where)->order('create_time desc')->select();
		foreach ($list as $rs) {
			$rs['datetime'] = date('Y-m-d H:i:s', $rs['create_time']);
			$new_list[] = $rs;
		}
		return $new_list;
	}
	/**
	 * 获取用户进行中订单数量
	 * @param  [type] $user_id 用户ID
	 */
	public function get_user_doing_num($user_id){
		$where['user_id'] = $user_id;
		$where['status']  = array('not in', array('cancel', 'finish'));
		$count = $this->where($where)->count();

		return $count ? $count : 0;
	}
	/**
	 * 获取用户已完成订单数量
	 * @param  [type] $user_id 用户ID
	 */
	public function get_user_finish_num($user_id){
		$where['user_id'] = $user_id;
		$where['status']  = 'finish';
		$count = $this->where($where)->count();

		return $count ? $count : 0;
	}
	/**
	 * 获取律师进行中订单数量
	 * @param  [type] $user_id 用户ID
	 */
	public function get_lawyer_doing_num($user_id){
		$where['lawyer_user_id'] = $user_id;
		$where['status']         = array('in', 'doing-lawyer,doing-audit');
		$count = $this->where($where)->count();

		return $count ? $count : 0;
	}
	/**
	 * 获取律师已完成订单数量
	 * @param  [type] $user_id 用户ID
	 */
	public function get_lawyer_finish_num($user_id){
		$where['lawyer_user_id'] = $user_id;
		$where['status']         = 'finish';
		$count = $this->where($where)->count();

		return $count ? $count : 0;
	}
	/**
	 * 获取律师等待处理订单数量
	 * @param  [type] $user_id 用户ID
	 */
	public function get_lawyer_wait_num($user_id){
		$where['lawyer_user_id'] = $user_id;
		$where['status']         = 'wait-lawyer';
		$count = $this->where($where)->count();

		return $count ? $count : 0;
	}
	/**
	 * 添加订单TODO
	 * @param [type] $order_sn 订单号
	 * @param [type] $content  内容
	 */
	public function add_todo($order_sn, $user_id, $content){
		if(!$order_sn){
			$this->tips_info = '订单号不能为空！';
			return false;
		}
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		if(!$content){
			$this->tips_info = '内容不能为空！';
			return false;
		}
		$data['type']        = 'lawyer_order_record';
		$data['user_id']     = $user_id;
		$data['order_sn']    = $order_sn;
		$data['content']     = $content;
		$data['create_time'] = time();
		D('OrderTodo')->add($data);
		$data['id'] = D('OrderTodo')->getLastInsID();
		$data['datetime'] = date('Y-m-d H:i:s', $data['create_time']);
		return $data;
	}
	/**
	 * 律师点击处理操作
	 * @param  [type] $order_sn 订单号
	 * @param  [type] $user_id  用户ID
	 */
	public function lawyer_click_handle($order_sn, $user_id){
		if(!$order_sn){
			$this->tips_info = '订单号不能为空！';
			return false;
		}
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		$where['lawyer_user_id'] = $user_id;
		$where['order_sn']       = $order_sn;
		if($this->where($where)->getField('status') == 'wait-lawyer'){
			$data['status']    = 'doing-lawyer';
			$data['edit_time'] = time();

			D('Order')->where($where)->save($data);
			return true;
		}
		return false;
	}
}



